import React from 'react';
import Item from './components/caseItem'
import useTitle from '../../hooks/useTitle';
import { useState, useEffect } from 'react'
import './index.css';
import axios from 'axios';
import HOST from '../../utils/const';

function Users() {
  useTitle(Users.title);
  const [detail, setDetail] = useState([]);
  const [register, setRegister] = useState(false);
  const [change, setChange] = useState(false);
  const [pageSize, setPageSize] = useState(5);
  const [pageNum, setPageNum] = useState(1);
  const [currentInfo, setCurrentInfo] = useState(getCurrentInfo());
  function remove(name){
    axios.get(HOST+`/method/monitor?case=3&username=${name}`).then((res)=>{
      switch (res.data) {
        case 'code=10\n': {
          alert('删除失败')
          setChange(!change)
          break;
        }
        case 'code=9\n': {
          alert('删除成功')
          setChange(!change)
          break;
        }
        default: {
          alert('未知错误');
          break;
        }
      }
    }).catch((err)=>{
      console.log(err);
    });
  }
  function newUser(){
    const psw = document.getElementById('username').value;
    const usn = document.getElementById('username').value;
    axios.get(HOST+`/method/register?username=${usn}&password=${psw}`).then((res)=>{
      switch (res.data) {
        case 'code=2\n': {
          alert('用户名已存在');
          setRegister(false);
          setChange(!change);
          break;
        }
        case 'code=1\n' :{
          alert('注册成功');
          setRegister(false);
          setChange(!change);
          break;
        }
        default: {
          alert('未知错误');
          setRegister(false);
          setChange(!change);
          break;
        }
      }
    }).catch((err)=>{
      console.log(err);
    })
  }
  useEffect(() => {
    axios.get(HOST+`/method/monitor?case=1`).then((res)=>{
      switch (res.data.split('\n')[0]) {
        case 'code=19': {
          setDetail(getResult(res.data.split('\n')))
          break;
        }
        default: {
          alert('未知错误');
          break;
        }
      }
    }).catch((err)=>{
      console.log(err);
    });
  }, [change])
  function getResult(str){
    const res = []
    for(let i=1;i<str.length;i++){
      str[i].split('\t')[0] && res.push(str[i].split('\t'))
    }
    return res;
  }
  function getCurrentInfo() {
    return detail.slice(pageSize * (pageNum - 1), pageSize * pageNum);
  }
  function updateCurrentInfo(size, num) {
    const res = detail.slice(pageSize * (num - 1), pageSize * num);
    if (res.length === 0) {
      const lastPage = Math.ceil(detail.length / pageSize);
      console.log(lastPage)
      setPageNum(lastPage);
      setPageSize(size)
    } else {
      setPageSize(size);
      setPageNum(num);
    }
  }

  function nextPage() {
    const lastPage = Math.ceil(detail.length / pageSize);
    if (pageNum === lastPage) {
      return
    }
    setPageNum(pageNum + 1)
  }

  function lastPage() {
    setPageNum(pageNum - 1)
  }

  useEffect(() => {
    setCurrentInfo(getCurrentInfo());
    // eslint-disable-next-line
  }, [pageSize, pageNum, detail])
  return (
    <div className='study'>
      <div className="mask" style={register ? {display: "block"}: {display: 'none'}}></div>
          <div className='register-box' 
          style={register ? {display: "flex",position: 'absolute', top:'100px', left:'0', zIndex: '100'}: {display: 'none'}}>
            <div className='inputframe'>
        <div>
        <div className='login-topbar'>
          <div className='topbar-sign'>注册</div>
        </div>
        <div className='devide-line'></div>
        </div>
        <div className='two-input'>
        <div className='username'>
        <div className='sign'>账号:</div>
          <input type="text" id='username' className='input-f'  placeholder='请输入账号'/>
        </div>
        <div className='password'>
          <div className='sign'>密码:</div>
          <input type="password" id='password' className='input-f' placeholder='请输入密码'/>
        </div>
        </div>
        <div className='button-box'>
        <button className='login-button' onClick={newUser}>
          注册
        </button>
        </div>
      </div>
    </div>
      <div className='study-topbar'>
      <div className='check-button-create'   onClick={() => { setRegister(true) }}>新建用户</div>
      </div>
      <div className='study-detail'>
        <div className='study-detail-topbar-users'>
          <div className='detail-casename'>用户名</div>
          <div className='detail-casepsw'>密码</div>
          <div className='detail-operation'>操作</div>
        </div>
        {currentInfo.map((item, index) => <Item detail={item} key={item} id={index+(pageNum-1)*pageSize} remove={remove} />)}
        <div className='study-detail-footbar'>
          <div className='case-total'>共 {detail.length} 条</div>
          <div className='case-pagesize'>
            <select className='pagesize-select' name='pagesize' id='pagesize' onChange={() => {
              updateCurrentInfo(Number(document.getElementById("pagesize").value), pageNum)
            }}>
              <option value="5">5条/页</option>
              <option value="10">10条/页</option>
            </select>
          </div>
          <div className='change-page'>
            <div className='last-page'>
              <div className='left-arrow' onClick={lastPage}></div>
            </div>
            <div className='current-page'>{pageNum}</div>
            <div className='next-page'>
              <div className='right-arrow' onClick={nextPage}></div>
            </div>
          </div>
          <div className='goto-page'>
            前往<input type="text" id='target-page' onBlur={
              (e) => {
                const res = Number(e.target.value)
                console.log(res);
                if (Number.isInteger(res)) {
                  const target = Math.round(res);
                  updateCurrentInfo(pageSize, target)
                }
              }
            } />页
      </div>
        </div>
      </div>
    </div>
  );
}

Users.path = '/users';
Users.title = '用户管理';
Users.meta = {
  keywords:
    '学习病例',
  description:
    '宠物医院 学习知识'
};
Users.exact = true;

export default Users;
